using System;
using OTE.Tasks.Commands.Category;
using SharpArch.Domain.Commands;
using SharpArch.NHibernate.Contracts.Repositories;

namespace OTE.Tasks.CommandHandlers.Category
{
    public class CategoryAddedHandler : ICommandHandler<CategoryAddedCommand>
    {
        private readonly INHibernateRepository<Domain.Category> _categoryRepository;

        public CategoryAddedHandler(INHibernateRepository<Domain.Category> categoryRepository)
        {
            _categoryRepository = categoryRepository;
        }

        public ICommandResult Handle(CategoryAddedCommand command)
        {
            var uow = _categoryRepository.DbContext;

            Domain.Category parentCat = null;
            if (command.ParentId > 0)
            {
                parentCat = _categoryRepository.Get(command.ParentId);
            }

            var category = new Domain.Category
                               {
                                   Parent = parentCat,
                                   Name = command.ContentName,
                                   CreatedBy = command.CreatedBy,
                                   CreatedDate = DateTime.Now,
                                   ModifiedDate = DateTime.Now,
                               };

            var cat = _categoryRepository.Save(category);

            uow.CommitChanges();

            var result = cat == null
                ? new CategoryAddedResult(false)
                : new CategoryAddedResult(true) { Category = cat };

            return result;
        }
    }
}